package com.two.lbms.utils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class CookieUtil {

    /**
     * 设置Cookie
     *
     * @param key      Cookie名称
     * @param value    Cookie Value
     * @param domain
     * @param response
     */
    public static void setCookie(String key, String value, HttpServletResponse response) {

        value = URLEncoder.encode(value, StandardCharsets.UTF_8);
        if (StringUtils.isNotBlank(value)) {
            value = value.replaceAll("\\+", "%20");
        }
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        // cookie.setDomain(domain);
        response.addCookie(cookie);
    }

    /**
     * 设置Cookie
     *
     * @param key      Cookie名称
     * @param value    Cookie Value
     * @param domain
     * @param response
     */
    public static void setCookieNoEncode(String key, String value, String domain,
                                         HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        // cookie.setDomain(domain);
        response.addCookie(cookie);
    }

    /**
     * 获取Cookie
     *
     * @param request
     * @param key
     *
     * @return
     */
    public static String getCookieValue(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        Cookie cookie = null;
        if (cookies != null) {
            for (Cookie value : cookies) {
                if (value.getName().equals(key)) {
                    cookie = value;
                }
            }
        }
        if (cookie != null) {
            return URLDecoder.decode(cookie.getValue(), StandardCharsets.UTF_8);
        }
        return null;
    }

    /**
     * 清除cookie
     *
     * @param cookieName
     * @param request
     * @param response
     */
    public static void deleteCookie(String cookieName, HttpServletRequest request,
                                    HttpServletResponse response) {
        Cookie[] arr_cookie = request.getCookies();
        if (arr_cookie != null) {
            for (Cookie cookie : arr_cookie) {
                if (cookie.getName().equals(cookieName)) {
                    cookie.setValue("");
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
    }
}
